<?php

namespace App\Service\Index;

use App\Constants\ErrorCode;
use App\Model\UserCoin;
use App\Model\UserProfile;
use App\Model\VoiceCall;
use App\Model\CallHangup;
use App\Service\CallBaseService;

/**
 * 一键语聊
 */
class QuickCallService extends CallBaseService
{
    protected function RoVerifyList()
    {
        return [
            'coin_option' => 'required|string'
        ];
    }


    public function handle()
    {
        $userId = $this->getUserId();
        $coinOption = $this->request->input('coin_option', '');
        $coinSetting = explode('-', $coinOption);

        //个人虚拟币账户信息
        $userCoin = UserCoin::getUserInfo($userId);
        //账户不够支付 3分钟的
        if (!$userCoin || !$userCoin['total_coin'] || $userCoin['total_coin'] < $coinSetting[0] * 3) {
            return $this->setError(ErrorCode::COIN_NOT_ENOUGH, '你的余额不足，请充值后再试~');
        }

        //获取指定的主播
        $hostId = $this->getHostsForQuick($userId, $coinSetting);
        if (!$hostId) {
            return $this->setError(ErrorCode::NO_VALID_HOST, '当前范围内的用户正在忙碌中，请稍后再试！');
        }

        $profile = UserProfile::getProfile($hostId);
        //发起语音通话
        $ret = VoiceCall::addRecord($userId, $hostId, VoiceCall::FROM_QUCIK, $profile->coin_setting);
        //呼叫回调
        $this->callHook($hostId);
        log_info(__CLASS__ . "=={$userId}==CoinOption:{$coinOption}==HostId:{$hostId}");
        return [
            'user_info' => UserProfile::buildHostItem($profile)
        ];
    }

    /**
     * 一键语聊-指定接听主播
     */
    function getHostsForQuick($userId = 0, $coinSetting = [])
    {
        //////// 测试 ////////
        if (check_dev_env()) return 3;

        $where = [
            ['role', UserProfile::ROLE_HOST],
            // ['online', 1]
        ];
        if (!empty($coinSetting)) {
            $where[] = ['coin_setting', '>=', $coinSetting[0]];
            $where[] = ['coin_setting', '<=', $coinSetting[1]];
        }
        $hostIds = UserProfile::where($where)->pluck('user_id')->toArray();
        $callingHosts = VoiceCall::getCallingHostIds();
        $hostIds = array_diff($hostIds, $callingHosts);
        //最近挂断用户的
        $hangupHosts = CallHangup::latestRecords($userId, 3);
        $hostIds = array_diff($hostIds, $hangupHosts);
        log_info(__CLASS__ . "=={$userId}==Calling:" . json_encode($callingHosts) . "==Hangup:" . json_encode($hangupHosts) . "==Hosts:" . json_encode($hostIds));
        if (empty($hostIds)) return 0;
        return $hostIds[array_rand($hostIds)];
    }
}
